// service/login/login.js
const app = getApp();
import http from "../../utils/http";
import util from "../../utils/util";
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		agree: false,
		code: "",
		avatarUrl: "",
		nickname: "",
		show: false,
		safeBottom: `30px`,
		config: "",
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		const high = app.globalData.safeBottom;
		this.setData({
			safeBottom: `${high}px`,
		});
		this.getCode();
	},
	onLoadConfig(option) {
		this.setData({
			config: app.globalData.config,
		});
	},
	chooseAvatar(e) {
		const { avatarUrl } = e.detail;

		http
			.upload(avatarUrl, {
				type: "image",
			})
			.then((res) => {
				this.setData({
					avatarUrl: res.data.url,
				});
			});
	},
	saveInfo() {
		http
			.post(
				"index/updateuserinfo",
				{
					type: "update",
					avatar: this.data.avatarUrl,
					nickname: this.data.nickname,
				},
				true,
				false
			)
			.then((res) => {
				this.setData({
					show: false,
				});
				util.toast(res.msg);
				wx.reLaunch({
					url: "/pages/index/index",
				});
			});
	},
	nameInput(e) {
		this.setData({
			nickname: e.detail.value,
		});
	},
	namereview(e) {
		console.log(e);
	},
	onClose() {
		this.setData({
			show: false,
		});
		wx.reLaunch({
			url: "/pages/index/index",
		});
	},
	getCode() {
		let that = this;
		wx.login({
			success(res) {
				if (res.code) {
					that.setData({
						code: res.code,
					});
				} else {
					this.getCode();
				}
			},
		});
	},

	read() {
		if (!this.data.agree) {
			wx.showToast({
				title: "请先阅读并同意《用户协议》《隐私政策》",
				icon: "none",
			});
		}
	},
	infoTap(e) {
		let info = e.currentTarget.dataset.info;
		let name = e.currentTarget.dataset.name;
		let id = app.globalData.config[info];
		util.skip("/service/info/info?id=" + id + "&name=" + name);
	},
	getPhoneNumber(e) {
		http
			.post(
				"user/userlogin",
				{
					code: this.data.code,
					type: 0,
					encryptedData: e.detail.encryptedData,
					iv: encodeURIComponent(e.detail.iv),
					leader_id: wx.getStorageSync("leader_id")
						? wx.getStorageSync("leader_id")
						: "",
				},
				true,
				false
			)
			.then((res) => {
				wx.setStorageSync("token", res.data.user.token);
				app.globalData.token = res.data.user.token;
				app.globalData.user = res.data.user;
				app.globalData.userInfo = res.data.userInfo;
				if (res.data.userInfo.is_update === 0) {
					this.setData({
						show: true,
						avatarUrl: res.data.user.avatar,
						nickname: res.data.user.nickname,
					});
				} else {
					wx.reLaunch({
						url: "/pages/index/index",
					});
				}
			})
			.catch((err) => {
				this.getCode();
			});
	},

	clickread() {
		this.setData({
			agree: !this.data.agree,
		});
	},
});
